package com.hoolai.qps.netty.echo;

import java.net.InetSocketAddress;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;

import com.hoolai.qps.netty.proto.Client;

public class LoopEchoClient extends Client {

    public static void main(String[] args) {
        try {
            new LoopEchoClient(new InetSocketAddress("192.168.1.215", 5555));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public LoopEchoClient(InetSocketAddress address) throws InterruptedException {
        ClientBootstrap bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(Executors
                .newCachedThreadPool(), Executors.newCachedThreadPool()));
        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            public ChannelPipeline getPipeline() throws Exception {
                return Channels.pipeline(new SimpleChannelUpstreamHandler(){
                    
                });
            }
        });
        bootstrap.setOption("remoteAddress", address);
        ExecutorService es = Executors.newFixedThreadPool(40);
        ConcurrentHashMap<Integer, Channel> channels = new ConcurrentHashMap<Integer, Channel>(2000);
        for (int i = 0; i < 1000; i++) {
            System.err.println(i); 
            final ChannelFuture future = bootstrap.connect();// connect
            final Channel channel = future.awaitUninterruptibly().getChannel();
            channels.put(channel.getId(), channel);
            Thread.sleep(10);
        }
        
        while(true) {
            for(final Channel channel : channels.values()) {
                es.submit(new Runnable() {
                    @Override
                    public void run() {
                        ChannelBuffer buffer = ChannelBuffers.buffer(1);
                        buffer.writeByte(1);
                        channel.write(buffer);
                    }
                });
//                Thread.sleep(1);
            }
        }
    }

}
